package com.xm9m.web.service.filter;

import com.salesmanager.core.utils.CoreConfiguration;
import com.salesmanager.web.constants.Constants;
import com.salesmanager.web.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Servlet Filter implementation class StoreFilter
 */

public class StoreFilter extends HandlerInterceptorAdapter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(StoreFilter.class);

    @Autowired
    private CoreConfiguration configuration;

    private final static String SERVICES_URL_PATTERN = "/services";
    private final static String REFERENCE_URL_PATTERN = "/reference";

    /**
     * Default constructor.
     */
    public StoreFilter() {

    }

    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {

        request.setCharacterEncoding("UTF-8");

        response.setHeader("X-Content-Type-Options","no");
        response.setHeader("X-Frame-Options","http://m.xm9m.com");

        /**
         * 设置唯一Cookie 用于数据统计，确定唯一用户
         */

//        String cookieId = (String)request.getSession().getAttribute(Constants.XM9M_COOKIE_ID);
//        if (cookieId == null){
//            Cookie[] cookies = request.getCookies();
//            //IOS ,Android原生请求 cookie为空
//            if (cookies != null) {
//                boolean hasCookieId = false;
//                for (Cookie cookie : cookies) {
//                    if (cookie.getName().equals("XM9M_COOKIE_ID")) {
//                        hasCookieId = true;
//                        cookieId = cookie.getValue();
//                        break;
//                    }
//                }
//                if (!hasCookieId) {
//                    cookieId = UUID.randomUUID().toString().replace("-", "");
//                    Cookie cookie = new Cookie(Constants.XM9M_COOKIE_ID, cookieId);
//                    response.addCookie(cookie);
//                }
//                request.getSession().setAttribute(Constants.XM9M_COOKIE_ID, cookieId);
//            }
//
//        }


        /**
         * 全局配置放入SESSION
         * 用于根据动态获取图片路径等功能
         */
//        CoreConfiguration config = (CoreConfiguration)request.getSession().getAttribute(Constants.STORE_CONFIGURATION);
//        if (config == null){
//            request.getSession().setAttribute(Constants.STORE_CONFIGURATION,configuration);
//        }


        return true;

    }
}
